<template>
  <div>
    <!--添加及编辑通用对话框-->
    <el-dialog
        :title="ruleFormCfg.title"
        :visible.sync="dialogVisible"
        @close="resetForm('ruleForm')"
        width="60%"
    >
      <el-form :model="ruleForm" status-icon :rules="ruleFormCfg.rules" ref="ruleForm">
        <el-form-item label="邮箱" prop="emailnumber">
          <el-input v-model="ruleForm.emailnumber" :disabled="ruleFormCfg.emailDisabled"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="pass">
          <el-input type="password" v-model="ruleForm.pass"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="emailpwd">
          <el-input type="password" v-model="ruleForm.emailpwd"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
          <el-button @click="resetForm('ruleForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-row :gutter="20">
      <el-col :span="8" class="float-card">
        <el-alert
            title="为避免第三方邮件发送服务,发送量过大容易被识别为垃圾邮件导致封禁,所以收件人越多,邮件发送的成功率越高"
            type="info"
            effect="dark"
            :closable="false">
        </el-alert>
        <el-divider content-position="left">操作</el-divider>
        <el-button type="primary" @click="openAdd()">添加收件人</el-button>
        <el-divider content-position="left">数据表</el-divider>
        <el-table
            v-loading="loading"
            stripe
            :data="senderTableData">
          <el-table-column
              fixed
              prop="id"
              label="编号"
              width="50">
          </el-table-column>
          <el-table-column
              prop="emailnumber"
              label="邮箱"
              width="180">
          </el-table-column>
          <el-table-column
              prop="emailpwd"
              label="密钥">
            <template v-slot="scope">
              {{ scope.row.emailpwd | hiddenKey }}
            </template>
          </el-table-column>
          <el-table-column
              fixed="right"
              label="操作"
              width="100">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="editThis(scope.row.id)">编辑</el-button>
              <el-button @click="deleteThisSender(scope.row.id)" type="text" size="small">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import {Message} from "element-ui";

export default {
  name: "SenderControl",
  data() {
    return {
      senderTableData: [],
      loading: false,
      dialogVisible: false,
      //表单对象
      ruleForm: {
        id: null,
        emailnumber: '',
        pass: '',
        emailpwd: ''
      },
      //表单配置对象
      ruleFormCfg: {
        title: '',
        url: '',
        rules: {},
        emailDisabled: false
      },
      //表单校验规则
      addRules: {
        pass: [
          {
            validator: (rule, value, callback) => {
              if (!value) {
                callback(new Error('密码不能为空!'));
              }
              callback();
            }, trigger: 'blur'
          }
        ],
        emailpwd: [
          {
            validator: (rule, value, callback) => {
              //检测非空 并且查看二次输入的密码是否相同
              if (!value) {
                callback(new Error('确认密码不能为空!'));
              } else if (value !== this.ruleForm.pass) {
                callback(new Error('两次输入的密码不一致!'));
              }
              callback();
            }, trigger: 'blur'
          }
        ],
        emailnumber: [
          {
            validator: (rule, value, callback) => {
              //正则表达式判断
              if (!/\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/.test(value)) {
                callback(new Error('邮箱格式不符合!'));
              }
              //遍历查询该邮箱是否已经存在
              let include = false;
              for (let i = 0; i < this.senderTableData.length; i++) {
                if (value === this.senderTableData[i].emailnumber) {
                  include = true;
                }
              }
              if (include) {
                callback(new Error('该邮箱已存在!'));
              }
              callback();
            }, trigger: 'blur'
          }
        ]
      }, editRules: {
        pass: [
          {
            validator: (rule, value, callback) => {
              if (!value) {
                callback(new Error('密码不能为空!'));
              }
              callback();
            }, trigger: 'blur'
          }
        ],
        emailpwd: [
          {
            validator: (rule, value, callback) => {
              //检测非空 并且查看二次输入的密码是否相同
              if (!value) {
                callback(new Error('确认密码不能为空!'));
              } else if (value !== this.ruleForm.pass) {
                callback(new Error('两次输入的密码不一致!'));
              }
              callback();
            }, trigger: 'blur'
          }
        ],
        emailnumber: [
          {
            validator: (rule, value, callback) => {
              //正则表达式判断
              if (!/\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/.test(value)) {
                callback(new Error('邮箱格式不符合!'));
              }
              callback();
            }, trigger: 'blur'
          }
        ]
      },
    }
  },
  mounted() {
    this.getSenderTableData();
  }, methods: {
    getSenderTableData() {
      this.loading = true;
      this.axios.get('emailPushModule/getSenders', {timeout: 10000}).then((rs) => {
        this.senderTableData = rs.data.content.senders;
        this.loading = false;
      });
    }, deleteThisSender(id) {
      this.$confirm('此操作将永久删除该发件人, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        let {data: rs} = await this.axios.delete(`emailPushModule/deleteThisSender?id=${id}`);
        if (rs) {
          return Message.success('删除成功');
        }
        Message.error('删除出现异常!');
      }).catch(() => {
        Message.info('已取消删除');
      }).finally(() => {
        this.getSenderTableData();
      });
    }, submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          //校验通过  判断依据:是否有id
          if (this.ruleForm.id) {
            //编辑提交
            let {data: rs} = await this.axios.put(this.ruleFormCfg.url, this.ruleForm);
            if (rs.code === 200) {
              Message.success('修改成功');
              this.dialogVisible = false;
            }
          } else {
            //添加提交
            let {data: rs} = await this.axios.post(this.ruleFormCfg.url, this.ruleForm);
            if (rs.code === 200) {
              Message.success('发件人添加成功');
              this.dialogVisible = false;
            }
          }
          this.getSenderTableData();
        } else {
          Message.warning('校验不通过,请重新输入!');
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    }, openAdd() {
      this.ruleForm.emailnumber = '';
      this.ruleFormCfg.title = '添加发件人';
      this.ruleFormCfg.url = 'emailPushModule/addOneSender';
      this.ruleFormCfg.rules = this.addRules;
      this.ruleFormCfg.emailDisabled = false;
      this.dialogVisible = true;
    },
    async editThis(id) {
      this.ruleForm.emailnumber = '';
      let {data: rs} = await this.axios.get(`/emailPushModule/getSenders?id=${id}`);
      this.ruleForm.emailnumber = rs.content.senders[0].emailnumber;
      this.ruleForm.emailpwd = '';
      this.ruleForm.pwd = '';
      this.ruleFormCfg.title = '编辑发件人';
      this.ruleFormCfg.url = 'emailPushModule/editThisSender';
      this.ruleFormCfg.rules = this.editRules;
      this.ruleFormCfg.emailDisabled = true;
      this.dialogVisible = true;
    }
  }, filters: {
    hiddenKey(value) {
      //只显示后四位
      return '*************' + value.substring(value.length - 4, value.length);
    }
  }
}
</script>

<style scoped>
.float-card {
  width: 600px;
}

@media screen and (max-width: 426px) {
  .float-card {
    width: 400px;
  }
}

@media screen and (max-width: 376px) {
  .float-card {
    width: 340px;
  }
}

@media screen and (max-width: 320px) {
  .float-card {
    width: 300px;
  }
}
</style>